<!--
  * lmabbe
  *
  * @Author:    lmabbe
  * @Date:      2025-06-26 19:25:24
  * @Copyright  lmabbe
-->
<template>
  <!---------- 查询表单form begin ----------->
  <div class="smart-query-form">
    <a-form size="small" style="margin-bottom: 10px">
      <a-row class="smart-query-form-row">
        <a-form-item class="smart-query-form-item" label="工单号查询">
          <a-input v-model:value="queryForm.workOrderCode" placeholder="工单号查询" style="width: 200px" />
        </a-form-item>
        <a-form-item class="smart-query-form-item" label="客户编号">
          <a-input v-model:value="queryForm.customerCode" placeholder="客户编号" style="width: 200px" />
        </a-form-item>
        <a-form-item class="smart-query-form-item" label="物料编码">
          <a-input v-model:value="queryForm.materialCode" placeholder="物料编码" style="width: 200px" />
        </a-form-item>
        <a-form-item class="smart-query-form-item" label="创建时间">
          <a-range-picker v-model:value="queryForm.createTime" :presets="defaultTimeRanges" style="width: 200px" @change="onChangeCreateTime" />
        </a-form-item>
        <a-form-item class="smart-query-form-item">
          <a-button type="primary" @click="onSearch">
            <template #icon>
              <SearchOutlined />
            </template>
            查询
          </a-button>
          <a-button class="smart-margin-left10" @click="resetQuery">
            <template #icon>
              <ReloadOutlined />
            </template>
            重置
          </a-button>
        </a-form-item>
      </a-row>
    </a-form>
    <!---------- 查询表单form end ----------->

    <!---------- 表格操作行 begin ----------->
    <a-row class="smart-table-btn-block">
      <div class="smart-table-operate-block">
        <a-button v-privilege="'workOrderInfo:add'" size="small" type="primary" @click="showForm">
          <template #icon>
            <PlusOutlined />
          </template>
          新建
        </a-button>
      </div>
    </a-row>
    <!---------- 表格操作行 end ----------->

    <!---------- 表格 begin ----------->
    <a-table
      v-privilege="'workOrderInfo:query'"
      :columns="columns"
      :dataSource="tableData"
      :loading="tableLoading"
      :pagination="false"
      :custom-row="
        (res) => {
          return {
            onclick: () => {
              onSelectChange(res.workOrderId);
            },
          };
        }
      "
      :row-selection="{ type: 'radio', selectedRowKeys: selectedRowKeyList, onChange: onSelectChange }"
      :scroll="{ y: 250 }"
      bordered
      rowKey="workOrderId"
      size="small"
    >
      <template #bodyCell="{ text, record, column }">
        <template v-if="column.dataIndex === 'orderStatus'">
          <span>{{ $smartEnumPlugin.getDescByValue('WORK_ORDER_STATUS', text) }}</span>
        </template>
        <template v-if="column.dataIndex === 'controlBarcodeFlag'">
          <span>{{ $smartEnumPlugin.getDescByValue('FLAG_BOOL_ENUM', text) }}</span>
        </template>
        <template v-if="column.dataIndex === 'disabledFlag'">
          <span>{{ $smartEnumPlugin.getDescByValue('FLAG_BOOL_ENUM', text) }}</span>
        </template>
        <template v-if="column.dataIndex === 'action'">
          <div class="smart-table-operate">
            <a-button v-privilege="'workOrderInfo:update'" type="link" @click="showForm(record)">编辑</a-button>
            <a-button v-privilege="'workOrderInfo:delete'" danger type="link" @click="onDelete(record)">删除</a-button>
          </div>
        </template>
      </template>
    </a-table>
    <!---------- 表格 end ----------->

    <div class="smart-query-table-page">
      <a-pagination
        size="small"
        v-model:current="queryForm.pageNum"
        v-model:pageSize="queryForm.pageSize"
        :defaultPageSize="queryForm.pageSize"
        :pageSizeOptions="PAGE_SIZE_OPTIONS"
        :show-total="(total) => `共${total}条`"
        :total="total"
        show-less-items
        showQuickJumper
        showSizeChanger
        @change="queryData"
        @showSizeChange="queryData"
      />
    </div>
  </div>
  <OrderTabs ref="orderTabsRef" />
  <WorkOrderInfoForm ref="formRef" @reloadList="queryData" />
</template>
<script setup>
  import { onMounted, reactive, ref } from 'vue';
  import { message, Modal } from 'ant-design-vue';
  import { SmartLoading } from '/@/components/framework/smart-loading';

  import { workOrderInfoApi } from '/@/api/business/product/order/work-order-info-api.js';
  import { smartSentry } from '/@/lib/smart-sentry';
  import WorkOrderInfoForm from './work-order-info-form.vue';
  import { defaultTimeRanges } from '/@/lib/default-time-ranges';
  import { PAGE_SIZE_OPTIONS } from '/@/constants/common-const';
  import OrderTabs from './orderTabs.vue';
  // ---------------------------- 表格列 ----------------------------

  const columns = ref([
    {
      title: '工单ID',
      dataIndex: 'workOrderId',
      ellipsis: true,
      width: 50,
      align: 'center',
    },
    {
      title: '工单编号',
      dataIndex: 'workOrderCode',
      ellipsis: true,
      width: 150,
      align: 'center',
    },
    {
      title: '客户简称',
      dataIndex: 'customerAbbreviation',
      ellipsis: true,
      width: 100,
      align: 'center',
    },
    {
      title: '订单状态',
      dataIndex: 'orderStatus',
      ellipsis: true,
      width: 100,
      align: 'center',
    },
    {
      title: '成品/机型编码',
      dataIndex: 'materialCode',
      ellipsis: true,
      width: 120,
      align: 'center',
    },
    {
      title: 'BOM版本',
      dataIndex: 'bomVer',
      ellipsis: true,
      width: 80,
      align: 'center',
    },
    {
      title: '成品/机型名称',
      dataIndex: 'materialName',
      ellipsis: true,
      width: 150,
      align: 'center',
    },
    {
      title: '成品/机型规格',
      dataIndex: 'materialSpec',
      ellipsis: true,
      width: 150,
      align: 'center',
    },
    {
      title: '成品/机型描述',
      dataIndex: 'materialDesc',
      ellipsis: true,
      width: 200,
      align: 'center',
    },
    {
      title: '单价',
      dataIndex: 'unitPrice',
      ellipsis: true,
      width: 80,
      align: 'center',
    },
    {
      title: '生产数量',
      dataIndex: 'productionQty',
      ellipsis: true,
      width: 80,
      align: 'center',
    },
    {
      title: '客户订单号',
      dataIndex: 'customerOrderCode',
      ellipsis: true,
      width: 120,
      align: 'center',
    },
    {
      title: '下单日期',
      dataIndex: 'orderTime',
      ellipsis: true,
      width: 150,
      align: 'center',
    },
    {
      title: '交货日期',
      dataIndex: 'deliveryDate',
      ellipsis: true,
      width: 150,
      align: 'center',
    },

    {
      title: '备注',
      dataIndex: 'remark',
      ellipsis: true,
      width: 200,
      align: 'center',
    },
    {
      title: '是否按发料条码上料',
      dataIndex: 'controlBarcodeFlag',
      ellipsis: true,
      width: 80,
      align: 'center',
    },
    {
      title: '禁用状态',
      dataIndex: 'disabledFlag',
      ellipsis: true,
      width: '80px',
      align: 'center',
    },
    {
      title: '创建人',
      dataIndex: 'createUserName',
      ellipsis: true,
      width: '80px',
      align: 'center',
    },
    {
      title: '创建时间',
      dataIndex: 'createTime',
      ellipsis: true,
      width: '150px',
      align: 'center',
    },
    {
      title: '更新人',
      dataIndex: 'updateUserName',
      ellipsis: true,
      width: '80px',
      align: 'center',
    },
    {
      title: '更新时间',
      dataIndex: 'updateTime',
      ellipsis: true,
      width: '150px',
      align: 'center',
    },
    {
      title: '操作',
      dataIndex: 'action',
      fixed: 'right',
      width: 150,
      align: 'center',
    },
  ]);

  // ---------------------------- 查询数据表单和方法 ----------------------------

  const queryFormState = {
    workOrderCode: undefined, //工单号查询
    customerCode: undefined, //客户编号
    materialCode: undefined, //物料编码
    createTime: [], //创建时间
    createTimeBegin: undefined, //创建时间 开始
    createTimeEnd: undefined, //创建时间 结束
    pageNum: 1,
    pageSize: 10,
  };
  // 查询表单form
  const queryForm = reactive({ ...queryFormState });
  // 表格加载loading
  const tableLoading = ref(false);
  // 表格数据
  const tableData = ref([]);
  // 总数
  const total = ref(0);

  // 重置查询条件
  function resetQuery() {
    let pageSize = queryForm.pageSize;
    Object.assign(queryForm, queryFormState);
    queryForm.pageSize = pageSize;
    queryData();
  }

  // 搜索
  function onSearch() {
    queryForm.pageNum = 1;
    queryData();
  }

  // 查询数据
  async function queryData() {
    tableLoading.value = true;
    try {
      let queryResult = await workOrderInfoApi.queryPage(queryForm);
      tableData.value = queryResult.data.list;
      total.value = queryResult.data.total;
      onSelectChange(tableData.value[0].workOrderId);
    } catch (e) {
      smartSentry.captureError(e);
    } finally {
      tableLoading.value = false;
    }
  }

  function onChangeCreateTime(dates, dateStrings) {
    queryForm.createTimeBegin = dateStrings[0];
    queryForm.createTimeEnd = dateStrings[1];
  }

  onMounted(queryData);

  // ---------------------------- 添加/修改 ----------------------------
  const formRef = ref();

  function showForm(data) {
    formRef.value.show(data);
  }

  // ---------------------------- 单个删除 ----------------------------
  //确认删除
  function onDelete(data) {
    Modal.confirm({
      title: '提示',
      content: '确定要删除选吗?',
      okText: '删除',
      okType: 'danger',
      onOk() {
        requestDelete(data);
      },
      cancelText: '取消',
      onCancel() {},
    });
  }

  //请求删除
  async function requestDelete(data) {
    SmartLoading.show();
    try {
      let deleteForm = {
        goodsIdList: selectedRowKeyList.value,
      };
      await workOrderInfoApi.delete(data.workOrderId);
      message.success('删除成功');
      queryData();
    } catch (e) {
      smartSentry.captureError(e);
    } finally {
      SmartLoading.hide();
    }
  }

  // ---------------------------- 批量删除 ----------------------------

  // 选择表格行
  const selectedRowKeyList = ref([]);

  // 批量删除
  function confirmBatchDelete() {
    Modal.confirm({
      title: '提示',
      content: '确定要批量删除这些数据吗?',
      okText: '删除',
      okType: 'danger',
      onOk() {
        requestBatchDelete();
      },
      cancelText: '取消',
      onCancel() {},
    });
  }

  //请求批量删除
  async function requestBatchDelete() {
    try {
      SmartLoading.show();
      await workOrderInfoApi.batchDelete(selectedRowKeyList.value);
      message.success('删除成功');
      queryData();
    } catch (e) {
      smartSentry.captureError(e);
    } finally {
      SmartLoading.hide();
    }
  }

  const orderTabsRef = ref();

  function onSelectChange(selectedRowKeys, v) {
    if (selectedRowKeys instanceof Array) {
      selectedRowKeys = selectedRowKeys[0];
    }
    selectedRowKeyList.value = [selectedRowKeys];
    let order = tableData.value.filter((item) => item.workOrderId === selectedRowKeys);
    orderTabsRef.value.setOrderInfo(order[0]);
  }
</script>